package cn.wolfcode.crm.shiro;


import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import lombok.Setter;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @program: crm
 * @description:
 * @author: Mr.chen
 * @create: 2018-07-09 13:23
 **/
public class EmployeeRealm extends AuthorizingRealm {
    @Setter
    private IEmployeeService employeeService;
    @Setter
    private IPermissionService permissionService;
    @Setter
    private IRoleService roleService;

    public String getName(){
        return "EmployeeRealm";
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        //获取页面传入的用户名
        String username = (String) token.getPrincipal();

        //根据用户名查询数据库
        Employee employee = employeeService.checkName(username);
        if (employee == null){
            return null;
        }
        //将数据库中员工数据封装到info对象返回, 进行下一步操作
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                employee,employee.getPassword(),getName());
        return info;
    }
    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //1.获取当前登录的用户信息
        Employee currentEmp = (Employee) principals.getPrimaryPrincipal();
        //2.根据用户id查询拥有的权限
        List<String> roles = new ArrayList<>();
        Set<String> permissions = new HashSet<>();
        //3.将角色和权限封装到info对象中, 让shiro进行下一步角色与权限的操作
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //判断是否是超级管理员
        if (currentEmp.getAdmin()==1){
            List<Role> list = roleService.list();
            for (Role role : list) {
                roles.add(role.getSn());
            }
            //permissions.add("*:*");
        }else{
            //根据登录用户id查询用户的角色
            List<Role> list = roleService.selectByEmpId(currentEmp.getId());
            for (Role role:list){
                roles.add(role.getSn());
                System.out.println(role);
            }
            //根据登录用户id查询用户的权限
            //permissions = permissionService.selectAllExpressionByEmpId(currentEmp.getId());
            //System.out.println(permissions.size());
        }
        permissions.add("*:*");
        info.addRoles(roles);
        info.addStringPermissions(permissions);
        return info;
    }
}
